import {useModel} from '@@/exports';
import {PlusOutlined} from '@ant-design/icons';
import type {ActionType, ProColumns} from '@ant-design/pro-components';
import {ProTable} from '@ant-design/pro-components';
import {Button, message, Popconfirm} from 'antd';
import React, {useRef, useState} from 'react';
import {
  deleteStepYieldOffsetUsingDELETE,
  listStepYieldOffsetUsingGET
} from "@/services/model/stepYieldOffsetController";
import AddOrEditModel from "@/pages/YieldOffset/StepYieldOffset/component/AddOrEditModel";

const StepYieldOffset: React.FC = () => {
  const {initialState} = useModel('@@initialState');
  const actionRef = useRef<ActionType>();
  const [selectProductSeriesValue, setSelectProductSeriesValue] = useState('');
  const [selectProductValue, setSelectProductValue] = useState('');
  const [selectStepValue, setSelectStepValue] = useState('');

  const [isModalOpen, setIsModalOpen] = useState(false);
  const [saveType, setSaveType] = useState('');
  const [editRecord, setEditRecord] = useState({} as API.StepYieldOffsetDTO);
  const handleAddBtn = () => {
    setIsModalOpen(true)
  }
  const initStepYieldOffsetList = async () => {
    const result = await listStepYieldOffsetUsingGET();
    return {
      data: result.data
    };
  }

  const onDelete = async (id: number) => {
    const result = await deleteStepYieldOffsetUsingDELETE({
      id,
      currentUserId: initialState?.currentUser?.id,
    });
    if (result.code === 0 && result.data) {
      message.success('删除成功');
      actionRef.current?.reload();
    } else {
      message.warning(result.message);
    }
  };
  const proColumns: ProColumns<API.StepYieldOffsetDTO>[] = [
    {
      title: '序号',
      key: 'index',
      render: (dom, entity, index) => (
        index + 1
      ),
    },
    {
      title: '产品系列编码',
      key: 'productSeriesCode',
      dataIndex: 'productSeriesCode',
      valueType: 'text',
    },
    {
      title: '产品系列名称',
      key: 'productSeriesName',
      dataIndex: 'productSeriesName',
      valueType: 'text',
    },
    {
      title: '产品编码',
      key: 'productCode',
      dataIndex: 'productCode',
      valueType: 'text',
    },
    {
      title: '产品名称',
      key: 'productName',
      dataIndex: 'productName',
      valueType: 'text',
    },
    {
      title: '工序编码',
      key: 'stepCode',
      dataIndex: 'stepCode',
      valueType: 'text',
    },
    {
      title: '工序名称',
      key: 'stepName',
      dataIndex: 'stepName',
      valueType: 'text',
    },
    {
      title: '目标良率',
      key: 'targetYield',
      dataIndex: 'targetYield',
      valueType: 'digit',
      render: (dom, entity) => (
        <span>{entity.targetYield === undefined || entity.targetYield === null ? '--' : (entity.targetYield * 100).toFixed(1) + '%'}</span>
      ),
    },
    {
      title: '阈值补偿',
      key: 'offsetThreshold',
      dataIndex: 'offsetThreshold',
      valueType: 'digit',
      render: (dom, entity) => (
        <span>{entity.offsetThreshold === undefined || entity.offsetThreshold === null ? '--' : (entity.offsetThreshold * 100).toFixed(1) + '%'}</span>
      ),
    },
    {
      title: '是否补偿良率',
      key: 'offset',
      dataIndex: 'offset',
      valueType: 'select',
      valueEnum: {
        1: {
          text: '是',
          status: 'Success',
        },
        0: {
          text: '否',
          status: 'Error',
        },
      },
    },

    {
      title: 'OFFSET值范围',
      key: 'offsetYield',
      valueType: 'digit',
      render: (dom, entity) => (
        <span>{entity.minOffsetYield === undefined || entity.minOffsetYield === null ? '' : (entity.minOffsetYield * 100).toFixed(1) + '%'} -&nbsp;
          {entity.maxOffsetYield === undefined || entity.maxOffsetYield === null ? '' : (entity.maxOffsetYield * 100).toFixed(1) + '%'}</span>
      ),
    },
    {
      title: '补偿后良率',
      key: 'finalYield',
      dataIndex: 'finalYield',
      valueType: 'digit',
      render: (dom, entity) => (
        <span>{entity.finalYield === undefined || entity.finalYield === null ? '--' : (entity.finalYield * 100).toFixed(1) + '%'}</span>
      ),
    },
    {
      title: '操作',
      valueType: 'option',
      render: (text, record) => [
        <a
          key="editable"
          onClick={() => {
            if (record.productCode) {
              setSelectProductValue(record.productCode);
            }
            if (record.productSeriesCode) {
              setSelectProductSeriesValue(record.productSeriesCode);
            }
            if (record.stepCode) {
              setSelectStepValue(record.stepCode);
            }
            setIsModalOpen(true);
            setEditRecord({
              ...record,
              minOffsetYield: record.minOffsetYield ? Number((record.minOffsetYield * 100).toFixed(1)) : undefined,
              maxOffsetYield: record.maxOffsetYield ? Number((record.maxOffsetYield * 100).toFixed(1)) : undefined,
              targetYield: record.targetYield ? Number((record.targetYield * 100).toFixed(1)) : undefined,
              offsetThreshold: record.offsetThreshold ? Number((record.offsetThreshold * 100).toFixed(1)) : undefined
            });
            setSaveType('edit')
          }}
        >
          编辑
        </a>,
        <Popconfirm
          key={'onDelete'}
          title="你想要删除这条数据吗"
          onConfirm={() => {
            onDelete(record.id)
          }}
          okText="Yes"
          cancelText="No"
        >
          <a key="deletable">删除</a>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <div>
      <div style={{display: "flex", justifyContent: "space-between", marginBottom: '5px'}}>
        <Button
          type="primary"
          onClick={() => {
            setSelectProductSeriesValue('');
            setSelectProductValue('')
            setSelectStepValue('')
            setEditRecord({} as API.StepYieldOffsetDTO)
            handleAddBtn();
            setSaveType('save')
          }}
          icon={<PlusOutlined/>}
        >
          新增 工序良率补偿
        </Button>
      </div>

      <ProTable<API.StepYieldOffsetDTO>
        rowKey="id"
        scroll={{x: 1100, y: 'calc(100vh - 205px)'}}
        actionRef={actionRef}
        headerTitle="工序良率补偿表格"
        columns={proColumns}
        search={false}
        pagination={false}
        request={() => initStepYieldOffsetList()}
      />

      <AddOrEditModel saveType={saveType}
                      isModalOpen={isModalOpen}
                      onCancel={() => setIsModalOpen(false)}
                      initProductCode={selectProductValue}
                      initProductSeriesCode={selectProductSeriesValue}
                      initStep={selectStepValue}
                      actionRef={actionRef}
                      editRecord={editRecord}
      />


    </div>
  );
};

export default StepYieldOffset;
